package fr.mystnihon.game.framework.impl.view;

import android.app.Activity;
import android.graphics.Canvas;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import fr.mystnihon.game.framework.impl.AndroidGame;

public class AndroidFastRenderView extends SurfaceView implements Callback {
	private static final String TAG = AndroidFastRenderView.class
			.getSimpleName();
	public MainThread thread;
	// private Actor player;
	AndroidGame game;

	public AndroidFastRenderView(AndroidGame game) {
		super(game);
		this.game = game;
		// make the GamePanel focusable so it can handle events
		setFocusable(true);
		getHolder().addCallback(this);
		thread = new MainThread(getHolder(), this);

		// player = new Actor(BitmapFactory.decodeResource(getResources(),
		// R.drawable.image), 10, 50);
	}

	/**
	 * Standard window-focus override. Notice focus lost so we can pause on
	 * focus lost. e.g. user switches to take a call.
	 */
	@Override
	public void onWindowFocusChanged(boolean hasWindowFocus) {
		if (!hasWindowFocus) {
			thread.pause();
		} else {
			thread.unpause();
		}
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
		// TODO Auto-generated method stub

	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		thread.setRunning(true);
		thread.start();

	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		// TODO Auto-generated method stub
		boolean retry = true;
		thread.setRunning(false);
		while (retry) {
			try {

				thread.join();
				retry = false;
			} catch (InterruptedException e) {
				// try again shutting down the thread
			}
		}
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (event.getAction() == MotionEvent.ACTION_DOWN) {

			// check if in the lower part of the screen we exit
			if (event.getY() > getHeight() - 50) {
				thread.setRunning(false);
				((Activity) getContext()).finish();
			}
		}
		// player.handleActions(event, this);
		game.getCurrentScreen().handleActions(event, this);

		return true;
	}

	synchronized public void update(long time) {
		// TODO Auto-generated method stub
		game.getCurrentScreen().update(time);
	}

	synchronized public void render(Canvas canvas) {
		game.getCurrentScreen().render(canvas);
	}

	public void stop() {
		thread.setRunning(false);
	}

	private void log(String msg) {
		Log.d(TAG, msg);
	}

}
